package com.cskaoyan.mall.dao.implement;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.mall.dao.OrderDao;
import com.cskaoyan.mall.model.sql.Orders;
import com.cskaoyan.mall.model.bo.ChangeOrderBO;
import com.cskaoyan.mall.model.bo.PageOrderBO;
import com.cskaoyan.mall.model.enumaration.OrderState;
import com.cskaoyan.mall.model.vo.OrderVO;
import com.cskaoyan.mall.model.vo.PageOrderInfoVO;
import com.cskaoyan.mall.model.vo.Spec;
import com.cskaoyan.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderDaoImpl implements OrderDao {
    private QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());

    /**
     * 分页查询的sql语句
     * select * from where ..... limit ? offset ? ;
     * @param orderBO
     * @return
     */
    @Override
    public List<PageOrderInfoVO> ordersByPage(PageOrderBO orderBO) {
        Map<String, Object> results = getDynamicSql(orderBO);
        String prefix_sql = "select id,userId,goodsDetailId,goods,spec,num as goodsNum,amount,stateId," +
        "nickname,name,address,phone ";
        String sql = (String) results.get("sql");
        List<Object> params = (List<Object>) results.get("params");
        params.add(orderBO.getPagesize());
        params.add((orderBO.getCurrentPage()-1)*orderBO.getPagesize());
        List<PageOrderInfoVO> query = null;
        try {
            query = runner.query(prefix_sql + sql + "limit ? offset ?",
                    new BeanListHandler<PageOrderInfoVO>(PageOrderInfoVO.class), params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(query==null) {
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return query;
    }

    /**
     * select count(id) from orders where ......
     * @param orderBO
     * @return
     */
    @Override
    public int getTotalCounts(PageOrderBO orderBO) {
        Map<String, Object> results = getDynamicSql(orderBO);
        String sql = (String) results.get("sql");
        List<Object> params = (List<Object>) results.get("params");
        String prefix_sql = "select count(id) ";
        Long query = null;
        try {
            query = (Long) runner.query(prefix_sql + sql, new ScalarHandler<>(), params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query.intValue();
    }

    @Override
    public OrderVO order(String id) {
        List<Spec> spec = null;
        OrderVO orderVOS = null;
        try {
            String sql1 = "select id,specName,unitPrice from spec where goodsId = (select goodsId from orders where " +
                    "id = ?)";
            spec = runner.query(sql1, new BeanListHandler<>(Spec.class), id);
            String sql = "select id,amount,num,goodsDetailId,stateId as state,goods from orders where id = ?";
            orderVOS = runner.query(sql,new BeanHandler<>(OrderVO.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        orderVOS.setSpec(spec);
        return orderVOS;
    }

    private Map<String, Object> getDynamicSql(PageOrderBO orderBO) {
        String base = "from orders where 1 = 1 ";
        List<Object> list = new ArrayList<>();
        if(orderBO.getState() != -1){
            base = base + " and stateId = ? ";
            list.add(orderBO.getState());
            System.out.println("add stateId");
        }
        if(!StringUtils.isEmpty(orderBO.getMoneyLimit1())){
            base = base + " and amount <= ? ";
            list.add(Double.parseDouble(orderBO.getMoneyLimit1()));
            System.out.println("add amount1");
        }
        if(!StringUtils.isEmpty(orderBO.getMoneyLimit2())){
            base = base + " and amount >= ? ";
            list.add(Double.parseDouble(orderBO.getMoneyLimit2()));
        }
        if(!StringUtils.isEmpty(orderBO.getGoods())){
            base = base + " and goods like ? ";
            list.add("%" + orderBO.getGoods() + "%");
        }
        if(!StringUtils.isEmpty(orderBO.getAddress())){
            base = base + " and address like ? ";
            list.add("%" + orderBO.getAddress() + "%");
            System.out.println("add address");
        }
        if(!StringUtils.isEmpty(orderBO.getName())){
            base = base + " and name like ? ";
            list.add("%" + orderBO.getName() + "%");
        }
        if(!StringUtils.isEmpty(orderBO.getId())){
            base = base + " and id = ? ";
            list.add(Integer.parseInt(orderBO.getId()));
        }
        Map<String,Object> map = new HashMap<>();
        map.put("sql",base);
        map.put("params",list);
        return map;
    }

    /**
     * 修改订单
     * 如果状态是已发货或者已经收到订单，则不能修改num和spec
     * @param changeOrderBO
     */
    @Override
    public void changeOrder(ChangeOrderBO changeOrderBO) {
        Orders orders = null;
        List<Object> params = new ArrayList<>();
        try {
            String base = "update orders set ";
            String sql = "select * from orders where id = ?";
            orders = runner.query(sql,new BeanHandler<>(Orders.class),changeOrderBO.getId());
            //查询订单表 ，返回订单数据
            if(orders.getStateId() == OrderState.DELIVERED.getCode() || orders.getStateId() == OrderState.RECEIVED.getCode() || orders.getStateId() == OrderState.UN_SHIPED.getCode()){
                base += "stateId = ? where id = ?";
                params.add(changeOrderBO.getState());
                params.add(changeOrderBO.getId());
            }else{
                base += "stateId = ? , spec = ? , num = ? where id = ?";
                params.add(changeOrderBO.getState());
                params.add(changeOrderBO.getSpec());
                params.add(changeOrderBO.getNum());
                params.add(changeOrderBO.getId());
            }
            runner.update(base,params.toArray());
            //更改订单表
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteOrder(String id) {
        try {
            runner.update("delete from orders where id = ?", id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void settleAccounts(Integer id, Integer goodsNum, Integer amount) {
        try {
            runner.update("update orders set num = ?,amount = ? ,stateId = ? where id = ?",
                    goodsNum,amount,1,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void pay(String id) {
        try {
            runner.update("update orders set stateId = 1 where id = ?",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void confirmReceive(String id) {
        try {
            runner.update("update orders set stateId = 3 where id = ?",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
